/*
 * This source code is part of TWaver 4.0
 *
 * Serva Software PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 * Copyright 2002 - 2011 Serva Software. All rights reserved.
 */

package demo.network.miscellaneous.cloudlayouter;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;

import twaver.Element;
import twaver.ResizableNode;
import twaver.network.CloudLayouter;
import twaver.network.TNetwork;

public class CustomCloudLayouter extends CloudLayouter{
	private Point lastMousePoint=null;
	private Element mouseOverElement = null;
	public CustomCloudLayouter(TNetwork network) {
		super(network);
	}

	protected void updateNode(Element item, int index, int count, double perspective) {
		DemoImageNode node=(DemoImageNode)item;
		if(lastMousePoint!=null){
			elementMouseOver();
		}
		node.putRenderAlpha((float)(0.2 + (perspective-0.4) * 0.5));
		Point point = node.getCenterLocation();
		double width=node.getImageWidth();
		double height=node.getImageHeight();
		if(width>height){
			if(width>100){
				height*=100d/width;
				width=100;
			}
		}else{
			if(height>100){
				width*=100d/height;
				height=100;
			}
		}
		Dimension canvasSize = network.getCanvasSize();
		double weight = (canvasSize.getWidth()+canvasSize.getHeight())/800/(0.7d+size()/50d);
		((ResizableNode)node).setSize((int)(width * (perspective-0.5)*weight)
				,(int)(height * (perspective-0.5)*weight));
		node.setCenterLocation(point.x,point.y);
	}
	
	protected boolean mouseMove(MouseEvent e) {
		lastMousePoint=e.getPoint();
		elementMouseOver();			
		return true;
	}

	private void elementMouseOver() {
		if(mouseOverElement==null||!network.getElementBounds(mouseOverElement).contains(lastMousePoint)){
			Element element=network.getElementPhysicalAt(lastMousePoint);
			if(element!=null&&!element.equals(mouseOverElement)){
				element.putLabelBorderColor(new Color(0,180,20));
				element.putLabelVisible(true);
			}
			if(mouseOverElement != null&&!mouseOverElement.equals(element)){
				mouseOverElement.putLabelBorderColor(new Color(128,128,128));
				mouseOverElement.putLabelVisible(false);
			}
			mouseOverElement=element;
		}
	}
	
	public Rectangle getLayoutRect() {
		double w = this.getNetwork().getCanvas().getWidth() / this.getNetwork().getZoom();
		double h = this.getNetwork().getCanvas().getHeight() / this.getNetwork().getZoom();
		return new Rectangle((int)(w / 6), (int)(h / 6), (int)(2d*w/3), (int)(2d*h/3));
	}
	
}